<template>
  <div class="goods-list">
    <!-- 搜索和操作区域 -->
    <div class="operation-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.title" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-cascader
            v-model="searchForm.categoryId"
            :options="categories"
            :props="{
              checkStrictly: true,
              value: 'id',
              label: 'name',
              children: 'children',
              emitPath: false
            }"
            placeholder="请选择分类"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="上架" :value="true" />
            <el-option label="下架" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">添加商品</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="goodsList"
      border
      style="width: 100%"
    >
      <el-table-column type="index" width="50" />
      <el-table-column prop="spu.title" label="商品名称" min-width="200">
        <template #default="{ row }">
          <div class="goods-info">
            <el-image
              :src="row.spu.mainImage"
              :preview-src-list="[row.spu.mainImage]"
              fit="cover"
              class="goods-image"
            />
            <span>{{ row.spu.title }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="spu.spuCode" label="商品编码" width="120" />
      <el-table-column label="价格区间" width="150">
        <template #default="{ row }">
          <div v-if="row.skuList && row.skuList.length > 0">
            ¥{{ getMinPrice(row.skuList) }} - ¥{{ getMaxPrice(row.skuList) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="库存" width="100">
        <template #default="{ row }">
          {{ getTotalStock(row.skuList) }}
        </template>
      </el-table-column>
      <el-table-column prop="spu.status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.spu.status ? 'success' : 'info'">
            {{ row.spu.status ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="spu.createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.spu.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button 
            type="primary" 
            link 
            @click="handleStatusChange(row)"
          >
            {{ row.spu.status ? '下架' : '上架' }}
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAdminGoodsList, deleteGoods, updateSpuStatus } from '@/api/goods'
import { getCategoryInfo } from '@/api/category'

const router = useRouter()
const loading = ref(false)
const goodsList = ref([])
const categories = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchForm = ref({
  title: '',
  categoryId: '',
  status: ''
})


// 获取商品列表
const getGoodsList = async () => {
  loading.value = true
  try {
    // 构建搜索参数
    const searchParams = {
      title: searchForm.value.title || undefined,
      categoryId: searchForm.value.categoryId || undefined,
      status: searchForm.value.status !== '' ? searchForm.value.status : undefined
    }

    // 调用接口，传入分页和搜索参数
    const res = await getAdminGoodsList(
      currentPage.value,
      pageSize.value,
      searchParams
    )
    
    // 处理响应数据
    if (res.items && Array.isArray(res.items)) {
      // 新的数据结构: { total: number, items: array }
      goodsList.value = res.items
      total.value = res.total || 0
    } else if (res.data && res.data.items && Array.isArray(res.data.items)) {
      // 可能的嵌套结构: { data: { total: number, items: array } }
      goodsList.value = res.data.items
      total.value = res.data.total || 0
    } else if (Array.isArray(res)) {
      // 旧的数据结构: 直接返回数组
      goodsList.value = res
      total.value = res.length
    } else {
      goodsList.value = []
      total.value = 0
      console.error('返回数据格式错误:', res)
    }
  } catch (error) {
    console.error('获取商品列表失败：', error)
    ElMessage.error('获取商品列表失败')
    goodsList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const getCategories = async () => {
  try {
    const res = await getCategoryInfo()
    categories.value = res
  } catch (error) {
    console.error('获取分类列表失败：', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 获取最低价格
const getMinPrice = (skuList) => {
  if (!skuList || skuList.length === 0) return '0.00'
  return Math.min(...skuList.map(sku => sku.price)).toFixed(2)
}

// 获取最高价格
const getMaxPrice = (skuList) => {
  if (!skuList || skuList.length === 0) return '0.00'
  return Math.max(...skuList.map(sku => sku.price)).toFixed(2)
}

// 获取总库存
const getTotalStock = (skuList) => {
  if (!skuList || skuList.length === 0) return 0
  return skuList.reduce((total, sku) => total + sku.stock, 0)
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getGoodsList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    title: '',
    categoryId: '',
    status: ''
  }
  handleSearch()
}

// 添加商品
const handleAdd = () => {
  router.push('/jiang/goods/add')
}

// 编辑商品
const handleEdit = (row) => {
  router.push(`/jiang/goods/edit/${row.spu.id}`)
}

// 修改商品状态
const handleStatusChange = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.spu.status ? '下架' : '上架'}该商品吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await updateSpuStatus(row.spu.id, !row.spu.status)
    
    ElMessage.success('操作成功')
    getGoodsList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改商品状态失败：', error)
      ElMessage.error('操作失败')
    }
  }
}

// 删除商品
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该商品吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteGoods(row.spu.id)
    
    ElMessage.success('删除成功')
    getGoodsList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败：', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  getGoodsList()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  getGoodsList()
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  getGoodsList()
  getCategories()
})
</script>

<style lang="scss" scoped>
.goods-list {
  .operation-area {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .search-form {
      flex: 1;
    }

    .operation-buttons {
      margin-left: 20px;
    }
  }

  .goods-info {
    display: flex;
    align-items: center;
    gap: 10px;

    .goods-image {
      width: 50px;
      height: 50px;
      border-radius: 4px;
    }
  }

  .pagination-area {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
